package com.acce.gxsc.page.registerCarRecord.child;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.common.Constants;
import com.acce.gxsc.common.QuizActivity;
import com.acce.gxsc.common.Tools;
import com.acce.gxsc.model.bean.PregisterBillStateEvent;
import com.acce.gxsc.model.netBean.CarPredictionBean;
import com.acce.gxsc.page.registerCarRecord.RegisterCarRecordFragment;
import com.acce.sdk.BaseActivity;
import com.acce.sdk.User;
import com.acce.sdk.base.mvp.BaseMvpFragment;
import com.acce.sdk.base.volleyHttp.GsonUtils;
import com.acce.sdk.utils.SharePreferencesManager;
import com.acce.sdk.utils.StringUtils;
import com.acce.sdk.widget.adapterrv.CommonAdapter;
import com.acce.sdk.widget.stickygridheaders.StickyGridHeadersBaseAdapter;
import com.acce.sdk.widget.stickygridheaders.StickyGridHeadersGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.acce.gxsc.common.Constants.ID_0;

/**
 * Created by huxley on 2017/5/26.
 */

public class RegisterCarRecordChildFragment extends BaseMvpFragment<RegisterCarRecordChildView, RegisterCarRecordChildPresenter> implements RegisterCarRecordChildView {

    boolean        isSelect;
    View           rootView;
    LayoutInflater mInflater;

    CommonAdapter<CarPredictionBean> mCommonAdapter;
    List<CarPredictionBean>          data;
    String                           mCompanyName;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout        mSwipeRefreshLayout;
    @Bind(R.id.sgv_handover)
    StickyGridHeadersGridView mSgvHandover;
    MyStickyGridHeadersBaseAdapter mAdapter;
    int                            lastVisibleItem;

    public static RegisterCarRecordChildFragment newInstance(boolean isSelect, String companyName) {
        Bundle args = new Bundle();
        args.putBoolean("isSelect", isSelect);
        args.putString("companyName", companyName);
        RegisterCarRecordChildFragment fragment = new RegisterCarRecordChildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected RegisterCarRecordChildPresenter createPresenter() {
        return new RegisterCarRecordChildPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_register_car_record_child, container, false);
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        init();
        mPresenter.loadRegisterCarInfo(false, "", "", null, mCompanyName);
        return rootView;
    }

    private void init() {
        mInflater = LayoutInflater.from(getContext());
        isSelect = getArguments().getBoolean("isSelect");
        mCompanyName = getArguments().getString("companyName");
        data = new ArrayList<>();

        mAdapter = new MyStickyGridHeadersBaseAdapter();
        mSgvHandover.setAdapter(mAdapter);


        mSwipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.material_blue, R.color.material_green);
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.loadRegisterCarInfo(false, ((RegisterCarRecordFragment) getParentFragment()).getNo(), ((RegisterCarRecordFragment) getParentFragment()).getType(), null, mCompanyName);
            }
        });

        mSgvHandover.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int newState) {
                if (!mSwipeRefreshLayout.isRefreshing() && newState == StickyGridHeadersGridView.SCROLL_STATE_IDLE && data != null &&
                        lastVisibleItem + 1 == (mAdapter.getCount() + data.size())) {
                    mPresenter.loadRegisterCarInfo(true, ((RegisterCarRecordFragment) getParentFragment()).getNo(), ((RegisterCarRecordFragment) getParentFragment()).getType(), null, mCompanyName);
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                lastVisibleItem = absListView.getLastVisiblePosition();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case 2001:
                CarPredictionBean carPrediction = (CarPredictionBean) data.getSerializableExtra("carPrediction");
                this.data.add(carPrediction);
                mCommonAdapter.notifyDataSetChanged();
                break;
            case 2002:
                String carPredictionString = new SharePreferencesManager(getContext()).readStringSharedPreferences(User.getInstance().getAtUserId());
                if (!StringUtils.isEmpty(carPredictionString)) {
                    com.acce.gxsc.model.loaclBean.CarPredictionBean carPredictionBean = GsonUtils.get().fromJson(carPredictionString, com.acce.gxsc.model.loaclBean.CarPredictionBean.class);
                    this.data = carPredictionBean.carPredictionBeen;
                    mCommonAdapter.getDatas().clear();
                    mCommonAdapter.getDatas().addAll(this.data);
                    mCommonAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void showProgressDialog(String s, boolean b) {
        ((BaseActivity) getActivity()).showProgressDialog(s, b);
    }

    @Override
    public void hideProgressDialog() {
        ((BaseActivity) getActivity()).hideProgressDialog();
    }

    @Override
    public void loadRegisterCarInfoSuccess(List<CarPredictionBean> datas) {
        this.data.clear();
        if (datas != null && datas.size() > 0) {
            this.data.addAll(datas);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPregisterBillStateEvent(PregisterBillStateEvent event) {
        mPresenter.loadRegisterCarInfo(false, event.preContainNo, event.pregisterBillState, null, mCompanyName);
    }

    Runnable openRunnable;
    Runnable closeRunnable;

    public void setRefreshing(boolean refreshing) {
        if (refreshing) {
            if (openRunnable == null) {
                openRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (mSwipeRefreshLayout != null) {
                            mSwipeRefreshLayout.setRefreshing(true);
                        }
                    }
                };
            }
            getActivity().getWindow().getDecorView().post(openRunnable);
        } else {
            if (closeRunnable == null) {
                closeRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (mSwipeRefreshLayout != null) {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    }
                };
            }
            getActivity().getWindow().getDecorView().postDelayed(closeRunnable, 300);
        }
    }


    //自定义adapter
    private class MyStickyGridHeadersBaseAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {

        MyStickyGridHeadersBaseAdapter() {
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ItemViewHolder ivh;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_register_car, parent, false);
                ivh = new ItemViewHolder();
                ivh.tvBoxNo = (TextView) convertView.findViewById(R.id.tv_box_no);
                ivh.tvSendCompany = (TextView) convertView.findViewById(R.id.tv_send_company);
                ivh.tvGoodsInfo = (TextView) convertView.findViewById(R.id.tv_goods_info);
                ivh.tvCustomerName = (TextView) convertView.findViewById(R.id.tv_customer_name);
                ivh.tvState = (TextView) convertView.findViewById(R.id.tv_state);
                convertView.setTag(ivh);
            } else {
                ivh = (ItemViewHolder) convertView.getTag();
            }
            int group = 0;
            while (position >= data.get(group).child.size()) {
                position -= data.get(group).child.size();
                group++;
            }
            final CarPredictionBean saleSheet = data.get(group).child.get(position);


            ivh.tvBoxNo.setText(Tools.getStringNonNull(saleSheet.preContainNo));
            ivh.tvSendCompany.setText(Tools.getStringNonNull(saleSheet.declareCompanyNick, saleSheet.consignorNick));
            ivh.tvGoodsInfo.setText(Tools.getStringNonNull(saleSheet.goodsInfo));
            ivh.tvCustomerName.setText(Tools.getStringNonNull(saleSheet.owerName));
            switch (saleSheet.pregisterBillState) {
                case "0":
                    ivh.tvState.setText("未进场");
                    ivh.tvState.setTextColor(Tools.getColor(R.color.red));
                    break;
                case "1":
                    ivh.tvState.setText("已进场");
                    ivh.tvState.setTextColor(Tools.getColor(R.color.yellow));
                    break;
                case "2":
                    ivh.tvState.setText("已离场");
                    ivh.tvState.setTextColor(Tools.getColor(R.color.green));
                    break;
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isSelect) {
                        Intent i = new Intent();
                        i.putExtra("pregisterKey", saleSheet.pregisterKey);
                        RegisterCarRecordChildFragment.this.getActivity().setResult(Activity.RESULT_OK, i);
                        RegisterCarRecordChildFragment.this.getActivity().finish();
                    } else {
                        Intent intent = new Intent(RegisterCarRecordChildFragment.this.getActivity(), QuizActivity.class);
                        intent.putExtra(Constants.Key.CATEGORY_ID, ID_0);
                        intent.putExtra("pregisterKey", saleSheet.pregisterKey);
                        RegisterCarRecordChildFragment.this.getActivity().startActivity(intent);
                    }
                }
            });
            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            int count = 0;
            for (int i = 0; i < data.size(); i++) {
                count += data.get(i).child.size();
            }
            return count;
        }

        @Override
        public int getNumHeaders() {
            return data.size();
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            TabViewHolder tvh;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_register_car_title, parent, false);
                tvh = new TabViewHolder();
                tvh.tvTab = (TextView) convertView.findViewById(R.id.tv_title);
                convertView.setTag(tvh);
            } else {
                tvh = (TabViewHolder) convertView.getTag();
            }
            CarPredictionBean saleSheet = data.get(position);
            tvh.tvTab.setText(saleSheet.createTime);
            return convertView;
        }

        @Override
        public int getCountForHeader(int header) {
            return data.get(header).child.size();
        }

        class TabViewHolder {
            TextView tvTab;
        }

        class ItemViewHolder {
            TextView tvBoxNo;
            TextView tvSendCompany;
            TextView tvGoodsInfo;
            TextView tvCustomerName;
            TextView tvState;
        }
    }
}
